//
//  NSString+Extension.m
//  OC_Poj_demo
//
//  Created by weixin on 2018/6/24.
//  Copyright © 2018年 weixn. All rights reserved.
//

#import "NSString+Extension.h"
#define TIME_ZONE @"Asia/Beijing"
@implementation NSString (Extension)

//拼接当前域名
-(NSString*)setURL_SERVICE{
    return [NSString stringWithFormat:@"%@%@",Main_Token_Model_MANAGER.RootUrl,self];
}


- (BOOL)isExist {
    if (self != nil && ![self isEqualToString:@""] && self.length > 0) {
        return YES;
    }
    
    return NO;
}




- (NSString *)convertCurrentTime {
    if (!self) {
        return nil;
    }
    //把字符串转为NSdate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *timeDate = [dateFormatter dateFromString:self];
    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:timeDate];
    long temp = 0;
    NSString *result;
    if (timeInterval/60 < 1)
    {
        result = [NSString stringWithFormat:@"刚刚"];
    }
    else if((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分钟前",temp];
    }
    else if((temp = temp/60) <24){
        result = [NSString stringWithFormat:@"%ld小时前",temp];
    }
    else if((temp = temp/24) <30){
        result = [NSString stringWithFormat:@"%ld天前",temp];
    }
    else if((temp = temp/30) <12){
        result = [NSString stringWithFormat:@"%ld月前",temp];
    }
    else{
        temp = temp/12;
        result = [NSString stringWithFormat:@"%ld年前",temp];
    }
    return result;
}

- (long )convertCurrentTimeChangeHours 
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *timeDate = [dateFormatter dateFromString:self];
    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:timeDate];
    long temp = timeInterval/3600;
    return temp;
}

/** 当前时间 YYYY-MM-dd HH:mm:ss*/
+ (NSString *)currentDatess{
    //今天
    NSDateFormatter *formater = [[ NSDateFormatter alloc] init];
    NSDate *curDate = [NSDate date];//获取当前日期
    [formater setDateFormat:@"YYYY-MM-dd HH:mm:ss"];//这里去掉 具体时间 保留日期
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:TIME_ZONE];
    [formater setTimeZone:timeZone];
    return  [formater stringFromDate:curDate];
}



- (NSString *)URLCharactersEncoding {
    
    NSString *encodedString = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)self,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,kCFStringEncodingUTF8));
    return encodedString;
}

- (NSString *)excludeSpace {
    if ([self isEqualToString:@" "] | [self isEqualToString:@"  "] | [self isEqualToString:@""]) {
        return nil;
    }
    return self;
}

//yyyy-MM-dd HH:mm:ss
+ (NSString *)currentDateDateFormatter:(NSString *)dateFormatterStr {
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormatterStr];
    return [dateFormatter stringFromDate:currentDate];
}

+ (NSString *)currentDate {
    
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    return [dateFormatter stringFromDate:currentDate];
    
}

- (NSString *)timeSegmentation {
    if ([self isContainStr:self judgeStr:@" "]) {
        NSArray *timeStrArr = [self componentsSeparatedByString:@" "];
        return timeStrArr.firstObject;
    }
    return self;
}
- (NSString *)stringReplaceSecurityStar {
    if (self.length > 0 && self) {
        NSMutableString *replace = [[NSMutableString alloc] initWithString:self];
        [replace replaceCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        return replace;
    }
    return self;
}
#pragma mark - 判断字符串(str)是否包含(judgeStr)
- (BOOL)isContainStr:(NSString *)str judgeStr:(NSString *)judgeStr {
    NSRange _range = [str rangeOfString:judgeStr];
    if (_range.location != NSNotFound) {
        
        return YES;
    }else {
        
        return NO;
    }
}
#pragma mark - 查找指定字符串的数量
- (NSInteger)countOccurencesOfString:(NSString *)searchString {
    NSInteger strCount = [self length] - [[self stringByReplacingOccurrencesOfString:searchString withString:@""] length];
    return strCount / [searchString length];
}


+(CGFloat)textWidth:(NSString *)text font:(CGFloat)font height:(CGFloat)height
{
    CGSize titleSize = [text boundingRectWithSize:CGSizeMake(10000,height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size;
    return titleSize.width;
}

+(CGFloat)textHeight:(NSString *)text font:(CGFloat)font width:(CGFloat)wideth
{
    CGSize titleSize = [text boundingRectWithSize:CGSizeMake(wideth,10000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size;
    return titleSize.height;
}

+(CGFloat)textFontHeight:(NSString *)text font:(UIFont*)font width:(CGFloat)wideth
{
    CGSize titleSize = [text boundingRectWithSize:CGSizeMake(wideth,10000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine  attributes:@{NSFontAttributeName:font} context:nil].size;
    return titleSize.height;
}


+(NSString *)stringFormatter:(NSString*)timeStr{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:timeStr];
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
    [dateFormatter2 setDateFormat:@"yyyy 年 MM 月 dd 日"];
    NSString *destDateString = [dateFormatter2 stringFromDate:date] ;
    return destDateString;
}

+ (NSString *)hexStringWithDecimaNumber:(NSUInteger)decimaNumber {
    
    char hexChar[8];
    sprintf(hexChar, "%x", (int)decimaNumber);
    
    NSString *hexString = [NSString stringWithCString:hexChar encoding:NSUTF8StringEncoding];
    
    return hexString;
}

- (NSString *)md5 {
    
    const char *cstr = [self UTF8String];
    
    unsigned char digest[16];
    
    CC_MD5(cstr, (unsigned int)strlen(cstr), digest);
    
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7],
            digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15]];
}


//判断如果包含中文
- (BOOL)containChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){ int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){
            return YES;
        }
    }
    return NO;
}

+ (NSString *)getHTMLFitStringWithBody:(NSString *)body maxWidth:(CGFloat)maxWidth {
    return kSTRING_FORMAT(@"<html>"
                          "<head>"
                          "</style>"
                          "<style>*{margin:3px 0px 3px 0px;padding:0 ;max-width:%f;}</style>"
                          "</head>"
                          "<body>%@</body>"
                          "</html>",maxWidth, body);
}

+ (NSString *)getJavaScriptFitString {
    return @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta)";
}

+  (BOOL)isBlankString:(NSString *)aStr {
    if (!aStr) {
        return YES;
    }
    if ([aStr isKindOfClass:[NSNull class]]) {
        return YES;
    }
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmedStr = [aStr stringByTrimmingCharactersInSet:set];
    if (!trimmedStr.length) {
        return YES;
    }
    return NO;
}

- (NSString *)removeSpaceAndNewline
{
    NSString *temp = [self stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return temp;
}


/**
 * 计算文字高度，可以处理计算带行间距的
 */
- (CGSize)boundingRectWithSize:(CGSize)size paragraphStyle:(NSMutableParagraphStyle *)paragraphStyle font:(UIFont*)font
{
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:self];
    [attributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.length)];
    [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, self.length)];
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin;
    CGRect rect = [attributeString boundingRectWithSize:size options:options context:nil];
    
    //    NSLog(@"size:%@", NSStringFromCGSize(rect.size));
    
    //文本的高度减去字体高度小于等于行间距，判断为当前只有1行
    if ((rect.size.height - font.lineHeight) <= paragraphStyle.lineSpacing) {
        if ([self containChinese:self]) {  //如果包含中文
            rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-paragraphStyle.lineSpacing);
        }
    }
    
    
    return rect.size;
}



/**
 * 计算文字高度，可以处理计算带行间距的
 */
- (CGSize)boundingRectWithSize:(CGSize)size font:(UIFont*)font  lineSpacing:(CGFloat)lineSpacing
{
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:self];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;
    [attributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.length)];
    [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, self.length)];
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin;
    CGRect rect = [attributeString boundingRectWithSize:size options:options context:nil];
    
    //    NSLog(@"size:%@", NSStringFromCGSize(rect.size));
    
    //文本的高度减去字体高度小于等于行间距，判断为当前只有1行
    if ((rect.size.height - font.lineHeight) <= paragraphStyle.lineSpacing) {
        if ([self containChinese:self]) {  //如果包含中文
            rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-paragraphStyle.lineSpacing);
        }
    }
    
    
    return rect.size;
}



/**
 *  计算最大行数文字高度,可以处理计算带行间距的
 */
- (CGFloat)boundingRectWithSize:(CGSize)size font:(UIFont*)font  lineSpacing:(CGFloat)lineSpacing maxLines:(NSInteger)maxLines{
    
    if (maxLines <= 0) {
        return 0;
    }
    
    CGFloat maxHeight = font.lineHeight * maxLines + lineSpacing * (maxLines - 1);
    
    CGSize orginalSize = [self boundingRectWithSize:size font:font lineSpacing:lineSpacing];
    
    if ( orginalSize.height >= maxHeight ) {
        return maxHeight;
    }else{
        return orginalSize.height;
    }
}

/**
 *  计算是否超过一行
 */
- (BOOL)isMoreThanOneLineWithSize:(CGSize)size font:(UIFont *)font lineSpaceing:(CGFloat)lineSpacing{
    
    if ( [self boundingRectWithSize:size font:font lineSpacing:lineSpacing].height > font.lineHeight  ) {
        return YES;
    }else{
        return NO;
    }
}
/**
 *  商品详情页地图地址
 */
+(NSString*)getMapImageView:(NSString*)location markers:(NSString*)markers {
    

    NSString *zoom = @"14";;
    NSString *size = [NSString stringWithFormat:@"%d*%d",(int)kScreenW,180];
    NSString *key =  @"9e9d6a34d399d6a3c57ed3a15c69e76e";
    
//    NSMutableDictionary *param = [NSMutableDictionary dictionary];
//    param[@"location"] =  @"116.481485,39.990464";
//    param[@"zoom"] =  @"16";
//    param[@"size"] =  [NSString stringWithFormat:@"%d*%d",300,300];
//    param[@"markers"] =  @"mid,,A:116.481485,39.990464";
//    param[@"key"] =  @"9e9d6a34d399d6a3c57ed3a15c69e76e";
    
    NSString *mapImage = [NSString stringWithFormat:@"%@location=%@,%@&zoom=%@&size=%@&markers=mid,,A:%@,%@&key=%@",getBizMap,markers,location,zoom,size,markers,location,key];
    
    return  mapImage;
    
}

+(bool)Mobile:(NSString*)mobile
{
    
    /**
     * 移动号段正则表达式
     */
    NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    /**
     * 联通号段正则表达式
     */
    NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    /**
     * 电信号段正则表达式
     */
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
    
    if (isMatch1 || isMatch2 || isMatch3) {
        return YES;
    }else{
        return NO;
    }
    
}

+(NSString *)convertToJsonData1:(NSDictionary *)dict;

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}
@end


